package com.dousb.cloudlibrary.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dousb.cloudlibrary.annotation.AuthCheck;
import com.dousb.cloudlibrary.common.BaseResponse;
import com.dousb.cloudlibrary.common.DeleteRequest;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.common.ResultUtils;
import com.dousb.cloudlibrary.constant.UserConstant;
import com.dousb.cloudlibrary.exception.BusinessException;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.model.dto.announcement.AnnouncementAddRequest;
import com.dousb.cloudlibrary.model.dto.announcement.AnnouncementQueryRequest;
import com.dousb.cloudlibrary.model.dto.announcement.AnnouncementUpdateRequest;
import com.dousb.cloudlibrary.model.entity.Announcement;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.AnnouncementVO;
import com.dousb.cloudlibrary.service.AnnouncementService;
import com.dousb.cloudlibrary.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 公告表接口
 */
@RestController
@RequestMapping("/announcement")
@Slf4j
public class AnnouncementController {

    @Resource
    private AnnouncementService announcementService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建公告表
     *
     * @param announcementAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addAnnouncement(@RequestBody AnnouncementAddRequest announcementAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(announcementAddRequest == null, ErrorCode.PARAMS_ERROR);
        //   在此处将实体类和 DTO 进行转换
        Announcement announcement = new Announcement();
        BeanUtils.copyProperties(announcementAddRequest, announcement);
        // 数据校验
        announcementService.validAnnouncement(announcement, true);
        // 写入数据库
//        if (announcementAddRequest.getIsActive().equals(AnnouncementStatusEnum.Draft.getValue())){
//            announcementAddRequest.setIsActive(0);
//        }
        boolean result = announcementService.save(announcement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newAnnouncementId = announcement.getId();
        return ResultUtils.success(newAnnouncementId);
    }

    /**
     * 删除公告表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteAnnouncement(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Announcement oldAnnouncement = announcementService.getById(id);
        ThrowUtils.throwIf(oldAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        // 管理员可删除
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = announcementService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新公告表（仅管理员可用）
     *
     * @param announcementUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAnnouncement(@RequestBody AnnouncementUpdateRequest announcementUpdateRequest) {
        if (announcementUpdateRequest == null || announcementUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //   在此处将实体类和 DTO 进行转换
        Announcement announcement = new Announcement();
        BeanUtils.copyProperties(announcementUpdateRequest, announcement);
        // 数据校验
        announcementService.validAnnouncement(announcement, false);
        // 判断是否存在
        long id = announcementUpdateRequest.getId();
        Announcement oldAnnouncement = announcementService.getById(id);
        ThrowUtils.throwIf(oldAnnouncement == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = announcementService.updateById(announcement);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取公告表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<AnnouncementVO> getAnnouncementVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Announcement announcement = announcementService.getById(id);
        ThrowUtils.throwIf(announcement == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(announcementService.getAnnouncementVO(announcement, request));
    }

    /**
     * 分页获取公告表列表（仅管理员可用）
     *
     * @param announcementQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Announcement>> listAnnouncementByPage(@RequestBody AnnouncementQueryRequest announcementQueryRequest) {
        long current = announcementQueryRequest.getCurrent();
        long size = announcementQueryRequest.getPageSize();
        // 查询数据库
        Page<Announcement> announcementPage = announcementService.page(new Page<>(current, size),
                announcementService.getQueryWrapper(announcementQueryRequest));
        return ResultUtils.success(announcementPage);
    }

    /**
     * 分页获取公告表列表（封装类）
     *
     * @param announcementQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<AnnouncementVO>> listAnnouncementVOByPage(@RequestBody AnnouncementQueryRequest announcementQueryRequest,
                                                                       HttpServletRequest request) {
        long current = announcementQueryRequest.getCurrent();
        long size = announcementQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Announcement> announcementPage = announcementService.page(new Page<>(current, size),
                announcementService.getQueryWrapper(announcementQueryRequest));
        // 获取封装类
        return ResultUtils.success(announcementService.getAnnouncementVOPage(announcementPage, request));
    }

    /**
     * 发布公告
     *
     * @param announcement
     * @param request
     * @return BaseResponse<Boolean>
     * @author 豆沙包
     * @date 2025/10/10 21:37
     */
    @PostMapping("/publish")
    public BaseResponse<Boolean> publish(@RequestBody Announcement announcement, HttpServletRequest request) {
        if (!announcementService.publishAnnouncement(announcement)) {
            return ResultUtils.success(false);
        }
        return ResultUtils.success(true);
    }
}
